<template>
  <div class='container'>
    <el-card class="box-card" shadow="never">

      <!-- 搜索 -->
      <el-form>
        <div class="filter-container">
          <el-col :span="8">
            <el-form-item label="关键字">
              <el-input style="width: 234px;" placeholder="根据文章标题搜索" class="filter-item" v-model="search.keyword" @change="loadArtList()"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-select style="width: 254px;" placeholder="请选择" v-model.trim="search.state" clearable filterable>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='4'>
            <el-button @click="handleClear">清除</el-button>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-col>
          <el-col :span="4">
            <el-button class="filter-item fr" size="small" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="dialogVisible = true">新增技巧</el-button>
          </el-col>
        </div>
      </el-form>
      <!-- 数据记录 -->
      <el-alert :title="alertText" type="info" class="alert" :closable="false" show-icon></el-alert>
      <!-- 数据列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column align="center" label="序号" type="index" :index="handleIndex">

        </el-table-column>
        <el-table-column align="center" label="文章标题">
          <template v-slot={row}>
            <span>{{row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="阅读数">
          <template v-slot={row}>
            <span>{{row.visits}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="录入人">
          <template v-slot={row}>
            <span>{{row.username}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="录入时间" :formatter="formatDate">
        </el-table-column>
        <el-table-column align="center" label="状态" :formatter="formatType">
          <!-- <template v-slot={row}>
            <span>{{row.state}}</span>
          </template> -->
        </el-table-column>
        <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
          <template v-slot={row}>
            <el-button type="text" @click="handleLook(row.id)">预览</el-button>
            <el-button type="text" @click="handleStatus(row)">
              <span v-if="row.state===0">启用</span>
              <span v-else>禁用</span>
            </el-button>
            <el-button type="text" :disabled="row.state===0 ?false:true" @click="handleEdit(row.id)">
              修改
            </el-button>
            <el-button type="text" :disabled="row.state===0 ?false:true" @click="handleDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <div class="pages">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="Number(requestParameters.page)" :total="Number(total)" :page-size="Number(requestParameters.pagesize)" :page-sizes="[5,10,20,30]" layout="->,sizes, prev, pager, next, jumper"></el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 新增标签的弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form ref="addRef" :model="rulesForm" style="width: 90%;" label-position="left" label-width="150px" :rules="rules">
        <el-form-item label="文章标题:" prop="title">
          <el-input placeholder="请输入文章标签" v-model="rulesForm.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容:" prop="articleBody" style="margin-top:30px">
          <div class="local-quill-editor">
            <quill-editor ref="myLQuillEditor" v-model="rulesForm.articleBody" :options="editorOption" class="editor">
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item label="视频地址:" prop="videoURL">
          <el-input placeholder="请输入视频地址" v-model="rulesForm.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 预览标签的弹窗 -->
    <el-dialog title="预览文章" :visible.sync="lookdialogVisible" width="60%" :before-close="handlelookClose">
      <div class="dialog">
        <el-form>
          <el-form-item><strong style="font-size:18px;">{{detail.title}}</strong></el-form-item>
          <el-form-item>{{moment(detail.createTime).format('YYYY-MM-DD HH:mm:ss')}}
            <template>
              {{formatmanager}}
            </template>
            <i class="el-icon-view"></i> {{detail.visits}}
          </el-form-item>
          <el-form-item class="line">
          </el-form-item>
          <el-form-item>
            <p v-html="detail.articleBody" style="background:#F8F8FF;font-size:16px"></p>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

  </div>

</template>

<script>
// 引入样式和quillEditor
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import { list, changeState, add, remove, detail, update } from '@/api/hmmm/articles.js'
import { status, manager } from '../../api/hmmm/constants'
import moment from 'moment'

// 工具栏配置项
const toolbarOptions = [
  // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['bold', 'italic', 'underline', 'strike'],
  // 引用  代码块-----['blockquote', 'code-block']
  ['blockquote', 'code-block'],
  // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ list: 'ordered' }, { list: 'bullet' }],
  // 链接、图片、视频-----['link', 'image', 'video']
  ['image', 'video']
]
export default {
  name: 'LocalQuillEditor',
  // 注册 quillEditor
  components: {
    quillEditor
  },
  data () {
    return {
      // 新增标签弹窗标志位
      dialogVisible: false,
      // 预览标签弹窗标志位
      lookdialogVisible: false,
      // 加载状态位
      loading: false,
      // select选择器
      options: [{
        value: 1,
        label: '启用'
      }, {
        value: 0,
        label: '禁用'
      }],
      // 状态
      status: status,
      // 数据列表
      tableData: [],
      // 分页数据
      requestParameters: {
        page: 1,
        pagesize: 10
      },
      // 总条数
      total: '',
      // 提示文本消息
      alertText: '',
      // 富文本编辑器
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: ''
      },
      // 表单内容
      rulesForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      // 表单验证规则
      rules: {
        title: [{
          required: true, message: '请输入文章标题', trigger: ['blur', 'change']
        }],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: ['blur', 'change'] }
        ]
      },
      // 详情内容
      detail: [],
      // 搜索 输入框内容
      search: {
        keyword: '',
        state: ''
      }

    }
  },
  computed: {
    title () {
      return this.rulesForm.id ? '修改文章' : '添加文章'
    },
    // 管理员状态
    formatmanager () {
      const info = manager.find(item => item.value === this.detail.creatorID)
      if (info) {
        return info.label
      } else {
        return '其他'
      }
    }

  },
  created () {
    this.loadArtList()
  },
  // 侦听
  watch: {
    detail: {
      handler (val) {
        // console.log(this.detail)
      },
      deep: true
    }
  },
  methods: {
    moment: moment,
    // 功能1：点击清除按钮，清除输入框中的内容
    handleClear () {
      this.search.keyword = ''
      this.search.state = ''
      this.loadArtList()
    },
    // 功能2：加载数据列表
    async loadArtList (params) {
      try {
        this.loading = true
        const ret = await list(this.requestParameters)
        if (ret.status === 200) {
          // 调用接口成功
          // console.log(ret)
          this.tableData = ret.data.items
          this.total = ret.data.counts
          this.alertText = `共 ${this.total} 条记录`
        } else {
          this.$message.error('加载文章列表失败')
        }
      } catch {
        this.$message.error('加载文章列表失败')
      } finally {
        this.loading = false
      }
    },
    // 功能3：分页
    // 3-1 每页显示信息条数
    handleSizeChange (val) {
      this.requestParameters.pagesize = val
      if (this.requestParameters.page === 1) {
        this.loadArtList(this.requestParameters)
      }
    },
    // 3-2 进入某一页
    handleCurrentChange (val) {
      this.requestParameters.page = val
      this.loadArtList()
    },
    // 3-3 动态索引序号
    handleIndex (index) {
      const { page, pagesize } = this.requestParameters
      return (page - 1) * pagesize + index + 1
    },
    // 功能4：启用禁用
    handleStatus (row) {
      if (row.state === 1) {
        row.state = 0
      } else {
        row.state = 1
      }
      // 文章状态
      changeState({
        id: row.id,
        state: row.state
      })
    },
    // 功能5：格式化时间
    formatDate (date) {
      // console.log(date)
      if (!date.createTime) return ''
      return moment(date.createTime).format('YYYY-MM-DD hh:mm:ss')
    },
    // 功能6:关闭弹窗
    handleClose () {
      // 弹窗关闭；清空表单；清空表单验证规则
      this.dialogVisible = false
      this.$refs.addRef.resetFields()
      // 清除表单内容（编辑权限的id）
      this.rulesForm = this.$options.data().rulesForm
    },
    handlelookClose () {
      this.lookdialogVisible = false
    },
    // 功能7:提交表单(新增+修改)
    handleSubmit () {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        // 验证通过 调用接口 刷新列表 关闭弹窗 清空表单
        if (this.rulesForm.id) {
          // 编辑
          try {
            const ret = await update(this.rulesForm)
            // console.log(ret)
            if (ret.status === 200) {
              this.loadArtList()
              this.$message.success('修改文章成功')
              this.dialogVisible = false
              this.$refs.addRef.resetFields()
              this.rulesForm = this.$options.data().rulesForm
            } else {
              this.$message.error('修改文章失败')
            }
          } catch {
            this.$message.error('修改文章失败')
          }
        } else {
          try {
            // 添加
            const ret = await add(this.rulesForm)
            if (ret.status === 200) {
              this.loadArtList()
              this.$message.success('添加文章成功')
              this.dialogVisible = false
              this.$refs.addRef.resetFields()
            } else {
              this.$message.error('添加文章失败')
            }
          } catch {
            this.$message.error('添加文章失败')
          }
        }
      })
    },
    // 功能8:删除
    async handleDel (id) {
      const ret = await this.$confirm('确认删除此文章吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (ret === 'cancel') return
      try {
        const retDel = await remove(id)
        // console.log(id)
        // console.log(retDel)
        if (retDel.status === 200) {
          // 删除成功，刷新列表
          this.$message.success('删除文章成功')
          this.loadArtList()
        } else {
          this.$message.error('删除文章失败')
        }
      } catch {
        this.$message.error('删除文章失败')
      }
    },
    // 功能9：预览
    async handleLook (id) {
      this.lookdialogVisible = true
      try {
        const ret = await detail(id)
        console.log(ret)
        if (ret.status === 200) {
          // 获取详情成功
          this.detail = ret.data
        } else {
          this.$message.error('获取详情失败')
        }
      } catch {
        this.$message.error('获取详情失败')
      }
    },
    // 功能10:修改
    async handleEdit (id) {
      const ret = await detail(id)
      if (ret.status === 200) {
        this.rulesForm = ret.data
        this.dialogVisible = true
      }
      // console.log(ret)
    },
    // 功能11:格式化状态形式
    formatType (row) {
      const info = this.status.find(item => parseInt(item.value) === parseInt(row.state))
      if (info) {
        return info.label
      } else {
        return '其他'
      }
    },
    // 功能12:搜索
    async handleSearch (id) {
      if (!id) {
        this.loadArtList()
      } else {
        const ret = await list({
          ...this.requestParameters,
          ...this.search
        })
        // console.log(ret)
        if (ret.status === 200) {
          this.tableData = ret.data.items
          this.total = ret.data.counts
          this.alertText = `共 ${this.total} 条记录`
        }
      }
    }
  }
}

</script>

<style scoped lang='less'>
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}

.box-card {
  margin: 10px;
}
.el-table th {
  background-color: #fafafa;
}
.el-table th.is-leaf {
  border-bottom: 2px solid #e8e8e8;
}
.editor {
  height: 150px;
  margin-bottom: 50px;
}
.line {
  border-bottom: 1px #ccc dotted;
}
.dialog {
  height: 450px;
  overflow: auto;
  ::-webkit-scrollbar {
    display: none;
    width: 0 !important;
  }
}
</style>
